package com.example.design.singleton;

/**
 * 懒汉模式
 * 虽然达到了按需初始化的目的，但却带来线程不安全的问题
 */
public class Singleton2 {
    private static Singleton2 INSTANCE;
    private Singleton2() {}
    // 线程不安全
    public static Singleton2 getInstance() {
        if (INSTANCE == null) {
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            INSTANCE = new Singleton2();
        }
        return INSTANCE;
    }

    // synchronized 修饰方法，线程安全，但效率低
    public static synchronized Singleton2 getInstance2() {
        if (INSTANCE == null) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            INSTANCE = new Singleton2();
        }
        return INSTANCE;
    }
    // synchronized 修饰代码块，线程安全，但效率还是低
    public static Singleton2 getInstance3() {
        if (INSTANCE == null) {
            // 双重检查锁
            synchronized (Singleton2.class) {
                if (INSTANCE == null) {
                    try {
                        Thread.sleep(1);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    INSTANCE = new Singleton2();
                }
            }
        }
        return INSTANCE;
    }
    public void m() {
        // ...
    }
}

class TestSingleton2 {
    public static void main(String[] args) {
        // 验证线程不安全
        /*for (int i = 0; i < 10; i++) {
            new Thread(()->{
                System.out.println(Singleton2.getInstance().hashCode());
            }).start();
        }*/

        /*for (int i = 0; i < 10; i++) {
            new Thread(()->{
                System.out.println(Singleton2.getInstance2().hashCode());
            }).start();
        }*/

        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                System.out.println(Singleton2.getInstance3().hashCode());
            }).start();
        }
    }
}